<!-- 富文本编辑器 -->
<template>
  <div id="richTextEditor">
    <!-- 工具栏 -->
    <Toolbar
      id="toolbar-container"
      :default-config="toolbarConfig"
      :editor="editorRef"
      mode="default"
    />
    <!-- 编辑器 -->
    <Editor
      id="editor-container"
      v-model="valueHtml"
      :default-config="editorConfig"
      mode="default"
      @on-change="handleChange"
      @on-created="handleCreated"
    />
  </div>
</template>
<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  defineEmits,
  defineProps,
  onBeforeUnmount,
  onUpdated,
  ref,
  shallowRef,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor, IToolbarConfig } from "@wangeditor/editor";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const props = defineProps<{
  modelValue: string;
}>();
const emit = defineEmits(["update:modelValue"]);
const toolbarConfig: Partial<IToolbarConfig> = {};
// 编辑器配置
const editorConfig = ref({
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      // 自定义图片上传
      async customUpload(file: any, insertFn: any) {
        // ALiControllerService.uploadImageUsingPost(file).then((res) => {
        //   insertFn(res.data);
        // });
        insertFn("https://picbed.shibalover.love/img/author.jpg");
      },
    },
  },
});
const handleCreated = (editor: any) => {
  editorRef.value = Object.seal(editor); // 记录 editor 实例，重要！
};

function handleChange(editor: any) {
  emit("update:modelValue", editor.getHtml());
  const toolbar = DomEditor.getToolbar(editor);

  const curToolbarConfig = toolbar.getConfig();
  console.log(curToolbarConfig.toolbarKeys);
}

// 内容 HTML
const valueHtml = ref();

onUpdated(() => {
  valueHtml.value = props.modelValue;
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped>
#richTextEditor {
  min-height: 40vh;
  border: solid 1px #e5e5e5;
}
</style>
